/*
 * Written by Guy Roberts of Object Skills Ltd, drifting
 * in cyberspace without a domain or email address right 
 * now. 
 * May 7 1993. You can use this as a base for a better application
 * as long as it is made publically available.
 */

#import "Preferences.h"
#define TITLE "Choose a directory" /* Should be in a string table */
#define IS_DIR(m)      (((m)&S_IFMT) == S_IFDIR)

@implementation Preferences

- init
{
	const char	*buffer = NXReadDefault(OWNER, "automaticallyLaunchEdit");
	
	[super init];

	if (buffer) {
		if (strcmp(buffer, "NO") == 0)
			launchEditAutomatically = NO;
		else if (strcmp(buffer, "YES") == 0)
			launchEditAutomatically = YES;
	}
	else
		launchEditAutomatically = YES;

	return self;
}

- showPreferencePanel: sender
{
	const char	*dir = NXReadDefault(OWNER, "defaultDirectory");

	[inspectorPanel makeKeyAndOrderFront: self];
	
	if (launchEditAutomatically)
		[[autoEditLaunchSwitch	setState: 1] display];
	else
		[[autoEditLaunchSwitch	setState: 0] display];

	if (dir)
		[directoryForm	setStringValue: dir at:0];
		
	return self;
}

- setManPageDirectory: sender
{
	const char	*dir = [sender stringValueAt:0];
	BOOL		isGoodDir = NO;
	char		badNews[1024];

	/* Check that this place is a directory and is writable */	
	{
		struct	stat	buffer;
		
		if (stat(dir, &buffer) == -1) {
			/* If it does not exist, try to fopen it */
			if (mkdir(dir, 0777) == -1) {
				sprintf(badNews, "Could not make the directory %s (errno %d)",
					dir, errno);
			}
			else
				isGoodDir = YES;
		}
		else {
			if (!IS_DIR(buffer.st_mode))
				sprintf(badNews, "%s is not a directory\n", dir);
			else if (access(dir, W_OK) != 0)
				sprintf(badNews, "Cannot access %s", dir);
			else
				isGoodDir = YES;
		}
	}
	
	if( !isGoodDir )
		NXRunAlertPanel(NULL, badNews, NULL, NULL, NULL, "me");
	else {
		/* Set the default value */
		NXWriteDefault(OWNER, "defaultDirectory", dir);
	}

	return self;
}

- toggleEditDefault: sender
{
	if ([sender	state] == 0) {
		launchEditAutomatically = NO;
		NXWriteDefault(OWNER, "automaticallyLaunchEdit", "NO");
	}
	else if ([sender	state] == 1) {
		launchEditAutomatically = YES;
		NXWriteDefault(OWNER, "automaticallyLaunchEdit", "YES");
	}

	return self;
}

